package com.cskaoyan.wordmemorize.common.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;

import java.text.SimpleDateFormat;

public class JsonUtil {
    private static final ObjectMapper objectMapper = new ObjectMapper();
    static {
        objectMapper.registerModule(new JavaTimeModule()); // 支持 Java 8 日期时间
        objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); // 禁用时间戳格式
        objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
    }

    /**
     * 将目标对象转化为Json字符串
     * @param object 目标对象
     * @return  Json字符串
     */
    public static String toJSON(Object object){
        try {
            String string = objectMapper.writeValueAsString(object);
            return string;
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 将对应的Json数据转化为对应的对象实例（Class<T> clazz）
     * @param jsonStr Json数据
     * @param clazz 对应的对象实例
     * @return
     * @param <T>
     */
    public static <T> T fromJSON(String jsonStr, Class<T> clazz){
        try {
            return objectMapper.readValue(jsonStr,clazz);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }
}
